<template>
    <div class="encyclopedia-manage">
        <el-tabs v-model="activeTab">
            <!-- 分类管理 -->
            <el-tab-pane label="分类管理" name="category">
                <el-row style="margin-bottom: 8px;">
                    <el-col>
                        <el-button type="success" icon="plus" @click="openCategoryDialog">新增分类</el-button>
                        <el-button type="primary" icon="refresh" @click="loadCategories">刷新</el-button>
                    </el-col>
                </el-row>

                <el-table :data="categoryList" border row-key="id"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <el-table-column label="分类名称" prop="name" width="300" />
                    <el-table-column label="父级分类" prop="parent_name" width="200">
                        <template #default="{ row }">
                            <span>{{ row.parent ? row.parent_name : '无' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" prop="order" width="100" />
                    <el-table-column label="描述" prop="description" />
                    <el-table-column label="操作" width="200" align="center">
                        <template #default="{ row }">
                            <el-button size="small" @click="editCategory(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="deleteCategory(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination background layout="prev, pager, next" :total="categoryTotal"
                        @current-change="handleCategoryPageChange" />
                </div>
            </el-tab-pane>

            <!-- 词条管理 -->
            <el-tab-pane label="词条管理" name="entry">
                <el-row style="margin-bottom: 8px;">
                    <el-col :span="8">
                        <el-select v-model="entryQuery.category_id" placeholder="选择分类" clearable @change="loadEntries">
                            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-col>
                    <el-col :span="8">
                        <el-button style="margin-left: 20px;" type="success" icon="plus"
                            @click="openEntryDialog">新增词条</el-button>
                        <el-button type="primary" icon="refresh" @click="loadEntries">刷新</el-button>
                    </el-col>
                    <el-col :span="8">
                        <el-input v-model="entryQuery.keyword" placeholder="搜索词条" clearable @change="loadEntries">
                            <template #append>
                                <el-button icon="search" />
                            </template>
                        </el-input>
                    </el-col>
                </el-row>

                <el-table :data="entryList" border>
                    <el-table-column label="标题" prop="title" show-overflow-tooltip />
                    <el-table-column label="分类" prop="category_name" width="200" />
                    <el-table-column label="浏览次数" prop="view_count" width="120" />
                    <el-table-column label="收藏次数" prop="favorite_count" width="120" />
                    <el-table-column label="更新时间" width="180">
                        <template #default="{ row }">
                            {{ formatTime(row.updated_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="300" align="center">
                        <template #default="{ row }">
                            <el-button size="small" @click="editEntry(row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="deleteEntry(row.id)">删除</el-button>
                            <el-button type="success" size="small" icon="upload" @click="showUploadDialog(row.id)">上传附件</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination">
                    <el-pagination background layout="prev, pager, next" :total="entryTotal"
                        @current-change="handleEntryPageChange" />
                </div>
            </el-tab-pane>
            <el-tab-pane label="附件管理" name="attachment">
      <el-row class="mb-2" style="margin-bottom: 8px;">
        <el-col :span="8">
          <el-input v-model="attachmentQuery.entry_id" placeholder="输入词条ID" clearable @change="loadAttachments">
            <template #append>
              <el-button icon="search" @click="loadAttachments" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="16" class="text-right">
          <el-button type="primary" icon="refresh" @click="loadAttachments">刷新</el-button>
        </el-col>
      </el-row>

      <!-- 附件列表 -->
      <el-table :data="attachmentList" border>
        <el-table-column prop="title" label="文件名" />
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.attachment_type)">
              {{ row.attachment_type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="deleteAttachment(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


    </el-tab-pane>
        </el-tabs>

        <!-- 上传附件对话框 -->
      <el-dialog title="上传附件" v-model="uploadDialogVisible">
        <el-form :model="uploadForm" label-width="100px">
          <el-form-item label="附件标题" prop="title">
            <el-input v-model="uploadForm.title" placeholder="请输入附件标题" />
          </el-form-item>
          <!-- <el-form-item label="关联词条">
            <el-input v-model="uploadForm.entry_id" placeholder="请输入词条ID" />
          </el-form-item> -->
          <el-form-item label="附件类型">
            <el-select v-model="uploadForm.attachment_type">
              <el-option label="文档" value="document" />
              <el-option label="图片" value="image" />
              <el-option label="视频" value="video" />
              <el-option label="音频" value="audio" />
            </el-select>
          </el-form-item>
          <el-form-item label="文件">
            <el-upload
              ref="uploadRef"
              :before-upload="beforeUpload"
              :limit="1"
              action="/api/hzadmin/public/upload_image/"
              :on-success="handleFileSuccess"
            >
              <el-button type="primary">选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持扩展名：.jpg, .jpeg, .png, .doc, .docx, .mp3, .mp4, .pptx, .pdf<br>
                  大小不超过50MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload">确认上传</el-button>
        </template>
      </el-dialog>

        <!-- 分类编辑对话框 -->
        <el-dialog :title="categoryForm.id ? '编辑分类' : '新增分类'" v-model="categoryDialogVisible">
            <el-form :model="categoryForm" :rules="categoryRules" label-width="100px">
                <el-form-item label="分类名称" prop="name">
                    <el-input v-model="categoryForm.name" />
                </el-form-item>
                <el-form-item label="父分类" prop="parent">
                    <el-select v-model="categoryForm.parent" placeholder="选择父分类" clearable>
                        <el-option v-for="item in parentCategoryOptions" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="排序" prop="order">
                    <el-input-number v-model="categoryForm.order" :min="0" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="categoryForm.description" type="textarea" rows="4" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="categoryDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveCategory">保存</el-button>
            </template>
        </el-dialog>

        <!-- 词条编辑对话框 -->
        <el-dialog :title="entryForm.id ? '编辑词条' : '新增词条'" v-model="entryDialogVisible" width="800px">
            <el-form :model="entryForm" :rules="entryRules" label-width="100px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="entryForm.title" />
                </el-form-item>
                <el-form-item label="分类" prop="category">
                    <el-select v-model="entryForm.category" placeholder="选择分类" clearable>
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="标签" prop="tags">
                    <el-input v-model="entryForm.tags" placeholder="多个标签用逗号分隔" />
                </el-form-item>
                <el-form-item label="摘要" prop="summary">
                    <el-input v-model="entryForm.summary" type="textarea" rows="3" />
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input v-model="entryForm.content" type="textarea" rows="8" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="entryDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEntry">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed,onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    category_list,
    category_create,
    category_update,
    category_delete,
    entry_list,
    entry_create,
    entry_update,
    entry_delete,
    entry_get,
    getEntryAttachments,
    uploadAttachment,
    deleteAttachment as deleteAttachmentApi
} from '/@/api/encyclopedia'
import dayjs from 'dayjs'
import { useUserConfig } from '/@/stores/UserInfoConfig'
const { userInfo } = useUserConfig()

const activeTab = ref('category')

// 附件管理相关状态
const attachmentList = ref([])
const attachmentQuery = reactive({
  entry_id: '',
  page: 1,
  page_size: 10
})
// 分类相关状态
const categoryList = ref([])
const categoryTotal = ref(0)
const categoryQuery = reactive({
    page: 1,
    page_size: 10
})
const categoryDialogVisible = ref(false)
const categoryForm = reactive({
    id: null,
    name: '',
    parent: null,
    order: 0,
    description: ''
})
// 词条表单状态
const entryDialogVisible = ref(false)
const entryForm = reactive({
    id: null,
    title: '',
    category: null,
    tags: '',
    summary: '',
    content: ''
})

// 词条相关状态
const entryList = ref([])
const entryTotal = ref(0)
const entryQuery = reactive({
    page: 1,
    page_size: 10,
    category_id: null,
    keyword: ''
})

// 上传相关状态
const uploadDialogVisible = ref(false)
const uploadForm = reactive({
  title: '',
  entry_id: '',
  file: null,
  attachment_type: 'document'
})
const uploadRef = ref(null)




// 加载分类数据
const loadCategories = async () => {
    const res = await category_list(categoryQuery)
    categoryList.value = res.data.categories
    categoryTotal.value = res.data.total
}

// 分类分页处理方法
const handleCategoryPageChange = (currentPage) => {
    categoryQuery.page = currentPage
    loadCategories()
}

// 加载词条数据
const loadEntries = async () => {
    const res = await entry_list(entryQuery)
    entryList.value = res.data.entries
    entryTotal.value = res.data.total
}

// 保存分类
const saveCategory = async () => {
    try {
        if (categoryForm.id) {
            await category_update(categoryForm.id, categoryForm)
        } else {
            await category_create(categoryForm)
        }
        ElMessage.success('保存成功')
        categoryDialogVisible.value = false
        loadCategories()
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 删除分类
const deleteCategory = async (info) => {
    if (info.children_count > 0) {
        ElMessage.error('该分类下存在子分类，无法删除')
        return
    }
    await ElMessageBox.confirm('确认删除该分类?', '警告', { type: 'warning' })
    const data = await category_delete(info.id)
    if (data.code == 200) {
        ElMessage.success('删除成功')
        loadCategories()
    } else {
        ElMessage.error(data.msg)
    }
}

// 打开分类对话框
const openCategoryDialog = () => {
    categoryForm.id = null
    categoryForm.name = ''
    categoryForm.parent = null
    categoryForm.order = 0
    categoryForm.description = ''
    categoryDialogVisible.value = true
}

const openEntryDialog = () => {
	const temp_add_baike_title = window.localStorage.getItem('temp_add_baike_title')
    entryForm.id = null
    entryForm.title = temp_add_baike_title ? temp_add_baike_title : ''
    entryForm.category = null
    entryForm.tags = ''
    entryForm.summary = ''
    entryForm.content = ''
    entryDialogVisible.value = true
}

// 编辑分类
const editCategory = (row) => {
    Object.assign(categoryForm, {
        id: row.id,
        name: row.name,
        parent: row.parent || null,
        order: row.order,
        description: row.description
    })
    categoryDialogVisible.value = true
}

const editEntry = async (row) => {
    try {
        const res = await entry_get(row.id)
        Object.assign(entryForm, {
            id: res.data.id,
            title: res.data.title,
            category: res.data.category,
            tags: res.data.tags,
            summary: res.data.summary,
            content: res.data.content
        })
        entryDialogVisible.value = true
    } catch (error) {
        ElMessage.error(error.message)
    }
}

const saveEntry = async () => {
    try {
        const payload = {
            ...entryForm,
            creator: userInfo.id,
        }

        if (entryForm.id) {
            await entry_update(entryForm.id, payload)
        } else {
            await entry_create(payload)
        }

        ElMessage.success('保存成功')
        entryDialogVisible.value = false
        loadEntries()
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 词条分页处理
const handleEntryPageChange = (currentPage) => {
    entryQuery.page = currentPage
    loadEntries()
}

// 删除词条
const deleteEntry = async (id) => {
    await ElMessageBox.confirm('确认删除该词条?', '警告', { type: 'warning' })
    const data = await entry_delete(id)
    if (data.code == 200) {
        ElMessage.success('删除成功')
        loadEntries()
    } else {
        ElMessage.error(data.msg)
    }
}

// 表单验证规则
const categoryRules = reactive({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    order: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
})

const entryRules = reactive({
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    category: [{ required: true, message: '请选择分类', trigger: 'change' }],
    summary: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
    content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
})

// 获取可选的父分类（排除自身）
const parentCategoryOptions = computed(() => {
    return categoryList.value.filter(c => c.id !== categoryForm.id)
})

// 分类选择项（扁平化处理）
const categoryOptions = computed(() => {
    const flattenCategories = (categories) => {
        return categories.reduce((acc, curr) => {
            acc.push({ id: curr.id, name: curr.name })
            if (curr.children) {
                acc.push(...flattenCategories(curr.children))
            }
            return acc
        }, [])
    }
    return flattenCategories(categoryList.value)
})

const formatTime = (timeString) => {
    return dayjs(timeString).format('YYYY-MM-DD HH:mm:ss')
}

// 文件类型验证
const beforeUpload = (file) => {
  const validExtensions = [
    '.jpg', '.jpeg', '.png',
    '.doc', '.docx',
    '.mp3', '.mp4',
    '.pptx', '.pdf'
  ]
  const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
  const isValid = validExtensions.includes(fileExtension)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValid) {
    ElMessage.error('不支持的文件格式')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过50MB')
    return false
  }
  return true
}

// 文件上传成功处理
const handleFileSuccess = (response) => {
  if (response.code === 200) {
    uploadForm.file = response.data
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}

// 显示上传对话框
const showUploadDialog = (entry_id) => {
  uploadDialogVisible.value = true
  Object.assign(uploadForm, {
    title: '',
    entry_id,
    file: null,
    attachment_type: 'document'
  })
  nextTick(() => {
    uploadRef.value?.clearFiles()
  })
}

// 提交附件信息
const submitUpload = async () => {
  if (!uploadForm.title.trim()) {
    ElMessage.warning('请输入附件标题')
    return
  }
  if (!uploadForm.entry_id) {
    ElMessage.warning('请输入关联词条ID')
    return
  }
  if (!uploadForm.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  try {
    const payload = {
      title: uploadForm.title,
      entry: uploadForm.entry_id,
      file_path: uploadForm.file,
      attachment_type: uploadForm.attachment_type
    }
    const res = await uploadAttachment(payload)
    if (res.code === 200) {
      ElMessage.success('附件上传成功')
      uploadDialogVisible.value = false
      loadAttachments()
    }
  } catch (error) {
    ElMessage.error('附件上传失败')
  }
}

// 加载附件列表
const loadAttachments = async () => {
  try {
    const res = await getEntryAttachments({
      entry_id: attachmentQuery.entry_id,
      page_size: attachmentQuery.page_size,
      page: attachmentQuery.page
    })
    if (res.code === 200) {
      attachmentList.value = res.data
    }
  } catch (error) {
    ElMessage.error('附件加载失败')
  }
}

// 删除附件
const deleteAttachment = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该附件？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteAttachmentApi(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadAttachments()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 类型标签样式
const getTagType = (type) => {
  const types = {
    image: 'success',
    video: 'danger',
    audio: 'warning',
    document: 'info'
  }
  return types[type] || 'info'
}


// 初始化加载数据
onMounted(() => {
    loadCategories()
    loadEntries()
    loadAttachments()
	//是否是从识别页面跳转过来的。如果是则自动填充词条标题
	const temp_add_baike_title = window.localStorage.getItem('temp_add_baike_title')
	if(temp_add_baike_title){
		entryForm.title = temp_add_baike_title
	}
})

onUnmounted(() => {
	//组件卸载时，清除本地存储
	window.localStorage.removeItem('temp_add_baike_title')
})
</script>

<style scoped>
.encyclopedia-manage {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.text-right {
    display: flex;
    justify-content: flex-end;
}
</style>
